package customerEnter.Frame.scanning.scanningServer;

import java.io.File;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import customerEnter.Frame.DaoDataTransmission.ConfigXml;
import customerEnter.Frame.DaoDataTransmission.ConfigXmlAttribute;
import customerEnter.Frame.DaoDataTransmission.ConfigXmlBean;
import customerEnter.Frame.scanning.ScanningAnalysis;

/**
 * 
 * 獲取xml 封裝bean 类名称：ConfigPackageServer 类描述： 创建人：dy 创建时间：2017-4-2 下午5:35:09
 * 
 */
public class ConfigPackageServer implements ScanningAnalysis {
	SAXReader	reader		= new SAXReader();
	Document	document	= null;
	Element		root		= null;
	@SuppressWarnings("rawtypes")
	Iterator	it			= null;
	ConfigXml	configXml	= new ConfigXml();

	/**
	 * 獲取被掃描的包名字
	 */
	public ConfigXml scanningConfigPackage(String path) throws DocumentException {
		initElement(document, path);
		List<ConfigXmlBean> configXmlBeans = new ArrayList<ConfigXmlBean>();
		initElementAll(it, configXmlBeans);
		configXml.setConfigXmlBeans(configXmlBeans);
		return configXml;
	}

	/**
	 * 初始化
	 */
	private void initElement(Document document, String path) throws DocumentException {
		document = reader.read(new File(path));
		root = document.getRootElement();
		it = root.elementIterator();
	}

	/**
	 * 把xml 文件轉換成bean
	 */
	@SuppressWarnings("rawtypes")
	public void initElementAll(Iterator iterator, List<ConfigXmlBean> configXmlBeans) {

		while (iterator.hasNext()) {
			Element element = (Element) iterator.next();
			Iterator eleIt = element.elementIterator();
			ConfigXmlBean configXmlBean = new ConfigXmlBean();
			// 設置名字
			configXmlBean.setLabelName(element.getName().trim());
			// 設置值
			configXmlBean.setValue(element.getText().trim());
			// 查找屬性
			Iterator attrIt = element.attributeIterator();

			List<ConfigXmlAttribute> configXmlAttributes = new ArrayList<ConfigXmlAttribute>();
			while (attrIt.hasNext()) {
				ConfigXmlAttribute configXmlAttribute = new ConfigXmlAttribute();
				Attribute a = (Attribute) attrIt.next();
				configXmlAttribute.setName(a.getName().trim());
				configXmlAttribute.setValue(a.getValue().trim());
				configXmlAttributes.add(configXmlAttribute);
			}
			// 放入屬性
			configXmlBean.setLabelAttributes(configXmlAttributes);
			configXmlBeans.add(configXmlBean);

			if (eleIt.hasNext()) {
				List<ConfigXmlBean> configXmlBeans2 = new ArrayList<ConfigXmlBean>();
				configXmlBean.setLabelBean(configXmlBeans2);
				initElementAll(eleIt, configXmlBeans2);
			}
		}
	}

}
